import axios from 'axios'
export default{
  // 开启命名空间
  namespaced:true,
  // 模块的数据
  state:{
    // 购物车的列表数据
    list:[]
  },
  mutations:{
    updateList(state,list){
      state.list=list
    },
    updateCount(state,{id,count}){
      // 根据id找到要修改的商品
      // console.log(id,count);
      const item = state.list.find(item => item.goods_id === id )
      if(item){
        // 修改该条商品的数量
        item.goods_count=count
      }
    },
    updateState(state,obj){
      const item = state.list.find(item => item.goods_id === obj.id)
      if(item){
        item.goods_state=obj.state
      }
    },
    updateAll(state,flag){
        state.list.forEach(item => {
          item.goods_state=flag
        }); 
      
    },
  },
  getters:{
    totalstate(state){
      return state.list.every(item=>item.goods_state)
    },
    totalCount(state){
      let count = 0
      state.list.forEach(item=>{
        if(item.goods_state){
          count+=item.goods_count
        }
      })
      return count    
    },
    totalPrice(state){
      let Price = 0
      state.list.forEach(item=>{
        if(item.goods_state){
          Price += item.goods_count*item.goods_price
        }
      })
      return Price 
    }
  },
  actions:{
    async getList(store){
      const res = await axios.get('https://applet-base-api-t.itheima.net/api/cart')
      console.log(res);
      store.commit('updateList',res.data.list)
    }
  }

}